package com.dys.service.impl;

import com.dys.dao.GoodsDao;
import com.dys.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @className: com.dys.service.impl.GoodsServiceImpl
 * @description: com.dys.service.impl
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/10/21 22:23
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;


    // @Transactional(readOnly = true) // 表示该方法中所有的数据库操作,只能是读取数据
    // @Transactional(timeout = 3, isolation = Isolation.DEFAULT) // 超时时间设置
    @Transactional
    @Override
    public void buyGoods(int userId, int goodsId) {
        try {
            TimeUnit.SECONDS.sleep(5);
            // 1.查询商品价格
            int price = goodsDao.findPriceById(goodsId);
            // 2.更新商品库存数量(扣库存成功)
            int count = goodsDao.updateGoodsStock(goodsId);
            System.out.println("受影响行数：" + count);
            // 3.更新用户的余额(减余额失败)
            int updateCount = goodsDao.updateUserBalance(userId, price);
            System.out.println("更新余额受影响行数：" + updateCount);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
